package com.itheima.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.tags.SecureTag;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by brss on 2018/6/25.
 */
@Controller
public class UserController {

    @RequestMapping("/add")
    public String add(){
        return "/user/add";
    }
    @RequestMapping("/update")
    public String update(){
        return "/user/update";
    }
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/Login")
    public String Login(String name,String password,Model model){

        /**
         * 使用Shiro编写认证操作
         */
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);

        //3.执行登录方法
        try {
            //无异常就登录成功
            subject.login(token);
            return "redirect:/test";

        }catch (UnknownAccountException e){
            e.printStackTrace();
            //登录失败:用户名不存在
            model.addAttribute("msg", "用户名不存在！");
            return "login";
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            //登录失败:密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }

    }

    /**
     * 测试Thymeleaf
     */
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("name", "海宝宝");
        return "test";
    }
}
